from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api import issues, users, cases, tickets, resources, auth, ai, attachments, reports, settings, comments
from app.database import engine, Base
# 导入所有模型以确保表创建
from app.models import user, issue, case, ticket, resource, attachment, comment

# 创建数据库表
try:
    Base.metadata.create_all(bind=engine)
except Exception as e:
    print(f"数据库连接或表创建失败: {e}")

app = FastAPI(title="Integrated Trouble Tracking System", version="1.0.0")

# 添加CORS中间件
# 使用更宽松的CORS配置来解决跨域问题
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 临时允许所有源来调试
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],  # 显式列出所有方法
    allow_headers=["*"],  # 允许所有头部
)

# 包含路由
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(users.router, prefix="/api/users", tags=["users"])
app.include_router(issues.router, prefix="/api/issues", tags=["issues"])
app.include_router(cases.router, prefix="/api/cases", tags=["cases"])
app.include_router(tickets.router, prefix="/api/tickets", tags=["tickets"])
app.include_router(resources.router, prefix="/api/resources", tags=["resources"])
app.include_router(attachments.router, prefix="/api/attachments", tags=["attachments"])
app.include_router(comments.router, prefix="/api/comments", tags=["comments"])
app.include_router(reports.router, prefix="/api/reports", tags=["reports"])
app.include_router(settings.router, prefix="/api/settings", tags=["settings"])
app.include_router(ai.router, prefix="/api/ai", tags=["ai"])

@app.get("/")
async def root():
    return {"message": "Welcome to Integrated Trouble Tracking System"}